const ordinary = {
    taskConfig: {
        taskList: [],
        taskStatus: false,
        taskNowIndex: 0,
        taskIdIndex: 0,
        errorTask: ''
    },
    taskTypeCode: {
        like_post: '点赞',
        save_post: '收藏',
        comment_post: '评论',
        follow_user: '关注用户'
    },
    resolveMsg: {},
    saveFileList: 0,
    saveFilePath: [],
    watchValue(key, newVal) {
        switch (key) {
            case 'taskList':
                if (!newVal.length) {
                    //无可执行任务
                } else {
                    //有可执行任务
                    console.log('有可执行任务，开始执行任务');
                    ordinary.openTask()
                }
                break;
            case 'taskStatus':
                if (newVal) {
                    //任务执行完毕
                    ordinary.saveFileList = 0
                    if (ordinary.saveFilePath.length) {
                        ordinary.saveFilePath.forEach((item) => {
                            files.remove(item)
                        })
                        ordinary.saveFilePath = []
                    }
                    Xhs.taskConfig.taskStatus = true
                }
                break;
            case 'taskNowIndex':
                let allTaskIndex = ordinary.taskConfig.taskList.length
                if (newVal < allTaskIndex) {
                    //还有新任务
                    ordinary.openTask()
                    return
                }
                ordinary.taskConfig.taskStatus = true
                break;
            case "errorTask":
                //上传报错任务日志
                let { taskNowIndex, taskList } = ordinary.taskConfig
                let idList = taskList[0].setting.batch_keyword
                let task_id = taskList[0].setting.task_id
                if (newVal && newVal >= idList.length) {
                    // 所有任务数据均执行异常
                    let params = {
                        taskType: task_id,
                        taskName: ordinary.taskTypeCode[task_id],
                        taskData: taskList[0].setting.batch_keyword,
                        errorTip: '日常任务执行异常,均执行失败',
                        taskDate: Comman.getDate()
                    }
                    Xhs.errorTask(params)
                    ordinary.taskConfig.taskStatus = true
                }
                break;
            default:
                break;
        }
    },
    init(data) {
        ordinary.taskConfig = Comman.defineReactive({
            taskList: [],
            taskStatus: false,
            taskNowIndex: 0,
            taskIdIndex: 0,
            errorTask: 0,
        }, '', ordinary.watchValue)
        sleep(1000)
        ordinary.taskConfig.taskList = [
            data
        ]
    },
    start(data) {
        //初始化数据
        if (data.skey == 'comment_post') {
            let resolveMsg = data.setting.comment_group.length ? Comman.getRandomArrayItem(data.setting.comment_group) : {}
            ordinary.resolveMsg = resolveMsg
            if (resolveMsg.image || resolveMsg.video) {
                ordinary.resolveMiddle(resolveMsg)
            }
        }
        ordinary.init(data)
    },
    openTask() {
        //开启任务
        ordinary.taskConfig.errorTask = 0
        let { taskList, taskNowIndex, taskIdIndex } = ordinary.taskConfig
        let nowTaskConfig = taskList[taskNowIndex]
        let homeMnue = btnConfig.home.homeMnue
        //重置首页
        while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
            back();
            console.log('back...');
            sleep(2000);
        }
        if (nowTaskConfig.setting.batch_object == '1') {
            ordinary.toFollow(nowTaskConfig.setting.batch_keyword)
            return
        }
        setClip('')
        ordinary.toButton(nowTaskConfig.setting.batch_keyword, nowTaskConfig.skey)

    },
    toLike(likeBtn, index) {
        if (likeBtn) {
            if (likeBtn.bounds) {
                App.clickByBtn(likeBtn, 2)
            } else {
                App.click(btnConfig.post.likeBtn.position.x, btnConfig.post.likeBtn.position.y, 2)
            }
        } else {
            console.log('未查询到需要点赞：' + index);
            App.randomSleep(2, 5)
        }
    },
    toCollect(collectBtn, index) {
        if (collectBtn) {
            if (collectBtn.bounds) {
                App.clickByBtn(collectBtn, 2)
            } else {
                App.click(btnConfig.post.collectBtn.position.x, btnConfig.post.collectBtn.position.y, 2)
            }
        } else {
            console.log('未查询到需要收藏：' + index);
            App.randomSleep(2, 5)
        }
    },
    toResolve(resolveBtn, nowResolveInputBtn, index) {
        let resolveMsg = ordinary.resolveMsg
        let fristSeed = text('抢首评').findOne(2000)
        let filebtn = btnConfig.post.UploadfileBtn.default() || btnConfig.post.UploadfileBtn2.default()

        //没有任何回复内容，直接返回
        if (!resolveMsg.content && (!resolveMsg.image || !resolveMsg.video)) {
            return
        }
        // 保持内容文本为空
        setText(0, '')
        sleep(2000)
        //评论
        if (resolveBtn && nowResolveInputBtn) {
            if (resolveBtn.bounds) {
                App.clickByBtn(resolveBtn, 3)
            } else {
                App.click(btnConfig.post.resolveBtn.position.x, btnConfig.post.resolveBtn.position.y, 3)
            }
            if ((resolveMsg.image || resolveMsg.video) && ordinary.saveFileList) {

                if (fristSeed) {
                    back()
                    sleep(2000)

                }

                ordinary.chooseFile(fristSeed ? filebtn : null)
            }

            if (!resolveMsg.image && !resolveMsg.video) {
                // 没有图片上传
                if (nowResolveInputBtn.bounds) {
                    App.clickByBtn(nowResolveInputBtn, 3)
                } else {
                    App.click(btnConfig.post.resolveInputBtn.position.x, btnConfig.post.resolveInputBtn.position.y, 3)
                }
            }
            // 选中后处理留言内容
            if (resolveMsg.content) {
                setText(0, resolveMsg.content)
            }
            let seedBtn = btnConfig.post.infoSendBtn.default() || btnConfig.post.infoSendBtn2.default()
            if (seedBtn) {
                if (!Xhs.isTest) {
                    if (seedBtn.bounds) {
                        App.clickByBtn(seedBtn, 3)
                    } else {
                        App.click(btnConfig.post.infoSendBtn.position.x, btnConfig.post.infoSendBtn.position.y, 3)
                    }
                } else {
                    console.log('测试阶段-可以发送留言');
                    sleep(2000)
                    back()
                    sleep(2000)
                }
            } else {
                console.log('留言失败，反馈异常')
                ordinary.taskConfig.errorTask += 1
            }
        } else {
            console.log('未查询到评论按钮，反馈异常' + index)
            ordinary.taskConfig.errorTask += 1
        }
    },
    // 点赞/收藏/评论
    toButton(idList, type) {
        idList.forEach((id, index) => {
            if (id.includes('复制本条信息')) {
                home()
                setClip(id)
                sleep(2000)
                Xhs.openApp()
                App.randomSleep(2, 5)
                let viewBtn = btnConfig.post.viewBtn.default()
                if (viewBtn) {
                    if (viewBtn.bounds) {
                        App.clickByBtn(viewBtn, 2)
                    } else {
                        App.click(btnConfig.post.viewBtn.position.x, btnConfig.post.viewBtn.position.y, 2)
                    }
                    let textTip = text('当前内容无法展示').findOne(1000) || text('视频暂不可查看').findOne(1000)
                    if (!textTip) {
                        App.randomSleep(2, 5)
                        let likeBtn = btnConfig.post.likeBtn.default()
                        let collectBtn = btnConfig.post.collectBtn.default()
                        let resolveBtn = btnConfig.post.resolveBtn.default()
                        let nowResolveInputBtn = btnConfig.post.resolveInputBtn.default()
                        if (type == 'like_post') {
                            ordinary.toLike(likeBtn, index)
                        }
                        if (type == 'save_post') {
                            ordinary.toCollect(collectBtn, index)
                        }
                        if (type == 'comment_post') {
                            ordinary.toResolve(resolveBtn, nowResolveInputBtn, index)
                        }
                        App.randomSleep(2, 4)
                    } else {
                        // 查询不到
                        console.log('笔记异常，反馈异常')
                        ordinary.taskConfig.errorTask += 1
                    }
                    back()
                    sleep(2000)
                } else {
                    // 查询不到
                    console.log('未查询到查看笔记按钮，反馈异常')
                    ordinary.taskConfig.errorTask += 1
                    back()
                    sleep(2000)
                }
                App.randomSleep(2, 5)
            }
        });
        console.log('日常任务：执行完毕,准备执行下一个任务');
        ordinary.taskConfig.taskNowIndex += 1
    },
    toFollow(idList) {
        let homeBtn = btnConfig.home.homeBtn
        let searchIconBtn = btnConfig.home.searchIconBtn
        let searchBtn = btnConfig.search.searchBtn
        let searchInput = btnConfig.search.searchInput
        let searchTabBtn = btnConfig.search.searchTabBtn
        let userIsFollow = btnConfig.search.userIsFollow
        let userFollow = btnConfig.search.userFollow
        //点击首页
        let nowHomeBtn = homeBtn.default()
        if (!nowHomeBtn) {
            console.log('未定位到首页按钮，反馈异常');
            ordinary.taskConfig.errorTask = 999
            return
        }
        if (nowHomeBtn.bounds) {
            App.clickByBtn(nowHomeBtn, 3)
        } else {
            App.click(homeBtn.position.x, homeBtn.position.y, 3)
        }
        //点击搜索图标按钮
        let nowSearchIconBtn = searchIconBtn.default()
        if (!nowSearchIconBtn) {
            console.log('未查询到搜索按钮，反馈异常');
            ordinary.taskConfig.errorTask = 999
            return
        }
        if (nowSearchIconBtn.bounds) {
            App.clickByBtn(nowSearchIconBtn, 3)
        } else {
            App.click(searchIconBtn.position.x, searchIconBtn.position.y, 3)
        }
        setText(0, idList[0])
        let nowSearchBtn = searchBtn.default()
        if (!nowSearchBtn) {
            console.log('未查询到外层搜索按钮，反馈异常')
            ordinary.taskConfig.errorTask = 999
            return
        }
        if (nowSearchBtn.bounds) {
            App.clickByBtn(nowSearchBtn, 3)
        } else {
            App.click(searchBtn.position.x, searchBtn.position.y, 3)
        }

        let inputDom = searchInput.default()
        gestures([350, [300, 350], [300, 400]]);
        App.randomSleep(2, 3)

        if (!inputDom) {
            console.log('未查询到输入区域，反馈异常')
            ordinary.taskConfig.errorTask = 999
            return
        }
        let searchTab = searchTabBtn.default()
        if (!searchTab.length) {
            console.log('未查询到切换按钮，反馈异常')
            ordinary.taskConfig.errorTask += 1
            return
        }
        searchTab.forEach(element => {
            let userBtn = element.findOne(text('用户'))
            let userBtn2 = element.findOne(text('账号'))
            if (userBtn) {
                App.clickByBtn(userBtn, 2)
            }
            if (userBtn2) {
                App.clickByBtn(userBtn2, 2)
            }
        });
        //进入搜索页面并循环进行关注
        idList.forEach((id, index) => {
            App.clickByBtn(inputDom, 3)
            setText(0, id)
            sleep(2000)
            App.clickByBtn(nowSearchBtn, 3)

            let follow = userFollow.default()
            let isFollow = userIsFollow.default()
            if (follow) {
                //进行关注
                if (follow.bounds) {
                    App.clickByBtn(follow, 3)
                } else {
                    App.click(userFollow.position.x, userFollow.position.y, 3)
                }
                let nowFollowStatus = userIsFollow.default()
                if (nowFollowStatus) {
                    console.log('日常任务：关注成功--' + id);
                } else {
                    toast('关注失败，反馈异常')
                    ordinary.taskConfig.errorTask += 1
                }
            }
            if (isFollow) {
                console.log('日常任务：已是关注--' + id);
            }
            if (!isFollow && !follow) {
                // 没有关注/已关注状态
                console.log('日常任务：关注--用户id搜索异常,反馈异常')
                ordinary.taskConfig.errorTask += 1
            }
            App.randomSleep(3, 5)
        })
        App.randomSleep(3, 5)
        console.log('日常任务：关注--执行完毕,准备执行下一个任务');
        ordinary.taskConfig.taskNowIndex += 1
    },
    resolveMiddle(seed) {
        console.log('FUNCTION: resolveMiddle');
        let resource = []
        if (seed.image) {
            resource = seed.image.split(',')
        }
        if (seed.video) {
            resource.push(seed.video)
        }
        sleep(2000)
        if (resource.length) {
            myUi.setTopText(Comman.getDate() + ': 评论笔记：' + "准备资源中....")
            let num = 0
            resource.forEach((item, index) => {
                let urlName = item.split('/').slice(-1)[0]
                if (!urlName) {
                    console.log('回复任务：文件解析名称失败：' + item);
                    return
                }
                let filePath = Xhs.resourcePath + new Date().getTime() + '_' + urlName
                files.create(filePath)
                let fileStatus = files.createWithDirs(filePath)
                let response = http.get(item);
                if (response.statusCode == 200) {
                    let fileBytes = response.body.bytes();
                    files.writeBytes(filePath, fileBytes);
                    media.scanFile(filePath);
                    ordinary.saveFilePath.push(filePath)
                    num += 1
                    console.log('回复任务：文件下载完成：' + item + ' ---------NO：' + index);
                } else {
                    console.log('回复任务：文件解析名称失败' + response.statusCode);
                }
                sleep(500)
            })
            ordinary.saveFileList = num
        }
        sleep(1000)
    },
    chooseFile(pageFilebtn) {
        //点击加载文件按钮
        //第一种机型
        let filebtn = btnConfig.post.UploadfileBtn.default() || btnConfig.post.UploadfileBtn2.default()
        if (pageFilebtn) {
            filebtn = pageFilebtn
        }

        //第二种机型
        let filebtn2 = btnConfig.message.messageAttItemFileBtn.default()
        if (!filebtn && !filebtn2) {
            console.log('回复任务：无法获取文件选择按钮');
            App.randomSleep(3, 5)
            return
        }
        if (filebtn && !filebtn2) {
            if (filebtn.bounds) {
                App.clickByBtn(filebtn, true)
            } else {
                App.click(btnConfig.post.UploadfileBtn.position.x, btnConfig.post.UploadfileBtn.position.y, 5)
                App.click(btnConfig.post.UploadfileBtn2.position.x, btnConfig.post.UploadfileBtn2.position.y, 5)
            }
        }

        if (filebtn2 && !filebtn) {
            if (filebtn2.bounds) {
                App.clickByBtn(filebtn2, true)
            } else {
                App.click(filebtn.position.x, filebtn.position.y, true)
            }
        }

        // 等待文件选择界面加载完成
        let messageFileMenu = btnConfig.file.messageFileMenu.default()
        if (!messageFileMenu) {
            console.log('回复任务：无法加载文件选择界面');
            return
        }
        // 文件项加载
        let fileItem = btnConfig.file.messageFileItem.default()
        if (!fileItem.length) {
            console.log('回复任务：无法获取文件列表');
            return
        }
        fileItem.forEach(function (file, index) {
            if (index < ordinary.saveFileList) {
                App.clickByBtn(file, 2)
            }
        })
    }
}
module.exports = ordinary;